package com.top.art.aspect;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * The type Log aspect.
 *
 * @author hjh
 * @version 2020 /10/6-20:56
 */
@Slf4j
//@Component
//@Aspect
public class LogAspect {


    /**
     * Gets method.
     */
    @Pointcut("execution(* com.top..*Controller.*(..)) && !execution(* com.top.art.controller.PaperController.*(..))")
    public void getMethod() {

    }

    /**
     * Process object.
     *
     * @param joinPoint the join point
     * @return the object
     * @throws Throwable the throwable
     */
    @Around("getMethod()")
    public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object obj = null;
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            String[] classNameArray = method.getDeclaringClass().getName().split("\\.");
            String methodName = classNameArray[classNameArray.length - 1] + "." + method.getName();
            String params = buildParamsDefault(joinPoint);
            log.info("请求方法:[{}],REQUEST={}", methodName, params);
            obj = joinPoint.proceed();
        } finally {
            log.info("返回时间:[{}],RESPONSE=[{}]", (System.currentTimeMillis() - start), JSONObject.toJSON(obj));
        }
        return obj;
    }

    private String buildParamsDefault(ProceedingJoinPoint call) {
        String params = "[";
        for (int i = 0; i < call.getArgs().length; i++) {
            Object obj = call.getArgs()[i];
            if (i != call.getArgs().length - 1) {
                params += obj + ",";
            } else {
                params += obj + "]";
            }
        }
        return params;
    }
}
